package com.bsb.base.common.util;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;

import com.bsb.base.common.config.Global;





public class Base64ForImg {
	public static final String imagesBasePath = Global.getConfig("images.basePath");
	private static final Logger LOGGER = Logger.getLogger(Base64ForImg.class);
	// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
	public static String GetImageStr(String imgFilePath) {
		byte[] data = null;
		String s = "";
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgFilePath);
			data = new byte[in.available()];
			in.read(data);
			in.close();
			// 对字节数组Base64编码
			s = Base64.encodeBase64String(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return s;// 返回Base64编码过的字节数组字符串
	}

	// 对字节数组字符串进行Base64解码并生成图片
	public static boolean GenerateImage(String imgStr, String imgFilePath) {
		
		if (imgStr == null) {// 图像数据为空
			return false;
		}
		try {
			// Base64解码
			byte[] bytes = Base64.decodeBase64(imgStr.getBytes());
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imgFilePath);
			out.write(bytes);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	
	// 对字节数组字符串进行Base64解码并生成图片
	/**
	 * 
	 * @param imgStr 图片base64
	 * @param fileName 新文件名
	 * @param type 0 不需要删除文件  1 需要删除文件
	 * @param oldFileName  要删除的文件名
	 * @return
	 */
	public static boolean GenerateImageFile(String imgStr,String fileName,int type,String oldFileName ) {
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		long currentTimeMillis = System.currentTimeMillis();
        Date date = new Date(currentTimeMillis);
        String res = simpleDateFormat.format(date);
        CCORFile.createDir(imagesBasePath+res);
        if(type==1){
        	if(!StringUtils.isEmpty(oldFileName)){
        		String[] split = oldFileName.split(",");
    			for (String string : split) {
    				
    				int indexOf = string.indexOf("_");
    				if(indexOf>0){
    					String substring = string.substring(indexOf+1);
    					long lt = new Long(substring);
    					Date date2 = new Date(lt);
    					String fileRes = simpleDateFormat.format(date2);
    					CCORFile ccor=new CCORFile(); 
    					ccor.DeleteFolder(imagesBasePath+fileRes+"/"+string);
    				}
    			}
    		}
        }
        	
		if (imgStr == null) {// 图像数据为空
			return false;
		}
		try {
			// Base64解码
			byte[] bytes = Base64.decodeBase64(imgStr.getBytes());
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += 256;
				}
			}
			// 生成jpeg图片
			OutputStream out = new FileOutputStream(imagesBasePath+res+"/"+fileName);
			out.write(bytes);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	/**
	 * 
	 * @param imgStr 图片base64数组
	 * @param oldFileName 要删除的老文件名字 数组
	 * @return
	 */
	public static String GenerateImageBatch(String[] imgStr,String[] oldFileName ) {
		
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		long currentTimeMillis = System.currentTimeMillis();
        Date date = new Date(currentTimeMillis);
        String res = simpleDateFormat.format(date);
        String imgPath = getOsPath();
        
        CCORFile.createDir(imgPath+res);
        if(oldFileName!=null){
    			for (String string : oldFileName) {
    				
    				int indexOf = string.indexOf("_");
    				if(indexOf>0){
    					String substring = string.substring(indexOf+1);
    					long lt = new Long(substring);
    					Date date2 = new Date(lt);
    					String fileRes = simpleDateFormat.format(date2);
    					CCORFile ccor=new CCORFile(); 
    					ccor.DeleteFolder(imgPath+fileRes+"/"+string);
    				}
    			}
    		
        }
        	
		
		String[] str=null;
		if (imgStr == null) {// 图像数据为空
			return null;
		}
		try {
			if(imgStr!=null){
				str=new String[imgStr.length];
				int j=1;
				for (String string : imgStr) {
					byte[] bytes = Base64.decodeBase64(string.getBytes());
					for (int i = 0; i < bytes.length; ++i) {
						if (bytes[i] < 0) {// 调整异常数据
							bytes[i] += 256;
						}
					}
					//String uuid = IdGen.uuid();
					String uuid = ShortUuid.generateShortUuid();
					String fileName=uuid+j+"_"+currentTimeMillis;
					// 生成jpeg图片
					OutputStream out = new FileOutputStream(imgPath+res+"/"+fileName);
					out.write(bytes);
					out.flush();
					out.close();
					str[j-1]=fileName;
					j++;
					
				}
				
			}
			String join = StringUtils.join(str, ",");
			return join;	
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.warn("msg:图片上传错误"+e.getMessage());
			return null;
		}
	}
	
	/**
	 * 获取图片的真实路径
	 * @param imgName
	 * @return
	 */
	public static String getImageRealPath(String imgName){
		if(StringUtils.isEmpty(imgName)){
			LOGGER.info("图片名字为=="+imgName);
			return null;
		}
		int indexOf = imgName.indexOf("_");
		if(indexOf<0){
			LOGGER.info(imgName+"==图片名字格式错误");
			return null;
		}
		String imgPath = getOsPath();
		String substring = imgName.substring(indexOf+1);
		  String res;
	        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
	        long lt = new Long(substring);
	        Date date = new Date(lt);
	        res = simpleDateFormat.format(date);
		
		String imagePath = imgPath + res + "/" + imgName;
		return imagePath;
	}
	
	
	public static String getOsPath(){
		String imgPath = "";
		 String osName = System.getProperties().getProperty("os.name").toLowerCase();
         if(osName.contains("linux")){
        	 imgPath = imagesBasePath;
         }else if(osName.contains("windows")){
        	 imgPath =  "D:/home/images/";
         }
         return imgPath;
	}
	
}